package com.zhuhjay.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zhuhjay.ruiji.common.BaseContext;
import com.zhuhjay.ruiji.common.R;
import com.zhuhjay.ruiji.domain.AddressBook;
import com.zhuhjay.ruiji.service.IAddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ZhuHJay
 * @date 2022/5/17 11:58
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    private final IAddressBookService addressBookService;
    public AddressBookController(IAddressBookService addressBookService) {
        this.addressBookService = addressBookService;
    }

    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrent());
        addressBookService.save(addressBook);
        return R.success("添加成功");
    }

    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }

    @DeleteMapping
    public R<String> delete(Long ids){
        addressBookService.removeById(ids);
        return R.success("删除地址成功");
    }

    @GetMapping("/{id}")
    public R<AddressBook> query(@PathVariable("id") Long id){
        return R.success(addressBookService.getById(id));
    }

    @PutMapping("/default")
    public R<String> defaultAddr(@RequestBody AddressBook addressBook){
        // 取消用户的默认地址
        LambdaUpdateWrapper<AddressBook> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AddressBook::getUserId, BaseContext.getCurrent())
                .set(AddressBook::getIsDefault, 0);
        addressBookService.update(updateWrapper);

        // 设置默认地址
        addressBookService.update(new LambdaUpdateWrapper<AddressBook>()
                .eq(AddressBook::getId, addressBook.getId())
                .set(AddressBook::getIsDefault, 1));
        return R.success("设置成功");
    }

    @GetMapping("/default")
    public R<AddressBook> getDefaultAddr(){
        return R.success(addressBookService.getOne(new LambdaQueryWrapper<AddressBook>()
                .eq(AddressBook::getUserId, BaseContext.getCurrent())
                .eq(AddressBook::getIsDefault, 1)));
    }

    @GetMapping("/list")
    public R<List<AddressBook>> list(){
        return R.success(addressBookService.list(new LambdaQueryWrapper<AddressBook>()
                .eq(AddressBook::getUserId, BaseContext.getCurrent())));
    }

}
